package vip.zhenzicheng.springboot.redis.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis缓存相关配置
 *
 * @author zhenzicheng
 * @date 2022-08-22 16:06
 */
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
// @EnableCaching
public class RedisConfig {

  /**
   * 使用了自定义的redis缓存配置，则配置文件中spring.cache相关失效
   * 如果是@Bean标注的方法，参数默认从容器中获取
   */
  // @Bean
  // public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
  //   RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
  //   // 指定key使用String序列化，value使用Jackson序列化为json
  //   config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
  //       .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
  //
  //   // 保存配置文件中的内容
  //   CacheProperties.Redis redisProperties = cacheProperties.getRedis();
  //
  //   if (redisProperties.getTimeToLive() != null) {
  //     config = config.entryTtl(redisProperties.getTimeToLive());
  //   }
  //
  //   if (redisProperties.getKeyPrefix() != null) {
  //     config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
  //   }
  //
  //   if (!redisProperties.isCacheNullValues()) {
  //     config = config.disableCachingNullValues();
  //   }
  //
  //   if (!redisProperties.isUseKeyPrefix()) {
  //     config = config.disableKeyPrefix();
  //   }
  //
  //   return config;
  // }
  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    // String序列化key
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    // value使用fastJson序列化
    // FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
    redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    // redisTemplate.setValueSerializer(fastJsonRedisSerializer);
    redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
    // LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory();

    redisTemplate.setConnectionFactory(connectionFactory);
    return redisTemplate;
  }
}
